#include <iostream>
#include <string>

#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

#define N 2
#define NUM 1024

void Write(int fd)
{
    string str = "hello, I am child";
    pid_t self = getpid();
    char buffer[NUM];
    for (int number = 0; number < 5; ++number)
    {
        buffer[0] = '\0';
        snprintf(buffer, sizeof(buffer), "%s-pid: %d-num: %d", str.c_str(), self, number);
        write(fd, buffer, strlen(buffer));
        sleep(1);
    }
    cout << "pid: " << self << " Child write exit" << endl;
    sleep(3);
}

void Read(int fd)
{
    char buffer[NUM];
    pid_t id = getpid();
    while (true)
    {
        buffer[0] = '\0';
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0) {
            buffer[n] = '\0';
            cout << "parent read[" << id << "]: " << buffer << endl;
        }
        else
            cout << n << endl;
    }
}

void WaitChild(pid_t id)
{
    int state = 0;
    pid_t rid = waitpid(id, &state, 0);
    if (rid == id)
    {
        cout << "ret code: " << (state >> 7) << endl;
        if (!WIFEXITED(state))
            cout << "sign code: " << WEXITSTATUS(state) << endl;
    }
    else if (rid == -1)
        exit(3);
}

int main()
{
    int pipefd[N] = { 0 };
    int n = pipe(pipefd);
    if (n < 0)
        return 1;
    
    //child w   parent r
    pid_t id = fork();
    if (id == 0)
    {
        close(pipefd[0]);   //close read
        Write(pipefd[1]);
        close(pipefd[1]);
    }
    else if (id > 0)
    {
        close(pipefd[1]);   //close write
        
        Read(pipefd[0]);
        WaitChild(id);
        
        close(pipefd[0]);
    }
    else
        return 2;
    
    return 0;
}
